<template>
	<view class="box">
		<uni-card class="top-cord">
			<input type="text" v-model="froms.forms.title" placeholder="描述清楚标题更容易被看到哦~" class="title" />
			<textarea class="area" v-model="froms.forms.textarea" cols="30" rows="10" placeholder="请输入你的闲置介绍~~" />
			<uni-section title="只选择图片" type="line">
				<view class="example-body">
					<image v-for="(i,idx) in froms.imageValue" :key="idx" :src="i" class="imgs" />
					<view @click="uploads" class="bt" v-show="froms.imageValue.length<5">
						<image src="../../../static/img/图片.svg" class="btimg"></image>
					</view>
				</view>
			</uni-section>
		</uni-card>
		<uni-card class="top-cord">
			<uni-forms label-position="top" ref="valiForm" :rules="rules" :modelValue="valiFormData">
				<uni-forms-item label="原价/元" style="color: red;" required name="buy_price">
					<uni-easyinput v-model="valiFormData.buy_price" placeholder="请输入商品的原价" />
				</uni-forms-item>
				<uni-forms-item label="售价/元" style="color: red;" required name="price">
					<uni-easyinput v-model="valiFormData.price" placeholder="请输入你要出售的价格" />
				</uni-forms-item>

				<view style="font-weight: 800;">选择分类</view>
				<view class="list">
					<text class="item" v-for="(i,index) in goodslist.list" :key="i._id"
						:style="{background:index==idx?'#317eff':''}" @click="Child(i,index)">
						{{i.title}}
					</text>
				</view>
				<view style="font-weight: 800;">类目明细</view>
				<view class="list">
					<text class="item" v-for="i in goodslist.children" :key="i._id"
						:style="{background:goodslist.onselect.includes(i._id)?'#317eff':''}" @click="sel(i._id)">
						{{i.title}}
					</text>
				</view>
				<uni-forms-item label="添加标签" required name="arr">
					<uni-data-checkbox v-model="valiFormData.arr" multiple :localdata="hobbys.list" />
					<text style="margin-left: 70%;" @click="
						inputDialog.open()
					">自定义标签+</text>
				</uni-forms-item>
			</uni-forms>

			<button type="primary" @click="submits('valiForm')">提交</button>

		</uni-card>
		<!-- 输入弹出框 -->
		<uni-popup ref="inputDialog" type="dialog">
			<uni-popup-dialog ref="inputClose" mode="input" title="请输入标签名称" value="" placeholder="请输入内容"
				@confirm="dialogInputConfirm">
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		reactive,
		ref,
		getCurrentInstance,
		onMounted
	} from 'vue'
	import api from '../../api/index.js'
	let idx = ref(0)
	//请求商品分类数据
	let goodslist = reactive({
		list: [],
		isTrue: true,
		children: [],
		onselect: [],
	})
	//选中事件
	let sel = async (id) => {
		console.log('选择');
		goodslist.onselect.indexOf(id) == -1 ? goodslist.onselect.push(id) :
			goodslist.onselect.splice(goodslist.onselect.indexOf(id), 1)
	}
	let radios = reactive({
		radio: ''
	})
	let Child = async (arr, index) => {
		goodslist.children = arr.children
		idx.value = index
		goodslist.onselect = []
	}
	let China = async () => {
		let {
			data
		} = await api.get('/cp/goodsclass')
		goodslist.list = data
		goodslist.children = data[0]['children']
	}
	let Two = async () => {
		uni.request({
			url: 'http://127.0.0.1:3366/cp/goodsclass',
			data: {},
			method: 'GET',
			success: ({
				data
			}) => {
				// console.log('原生拿到的数据', data);
				goodslist.list = data
				goodslist.children = data[0]['children']
			},
			fail: (err) => {
				console.log('原生获取失败~');
			}
		})
	}
	onMounted(() => {
		// China()
		Two()
	})

	let {
		proxy
	} = getCurrentInstance()
	let hobbys = reactive({
		list: [{
			text: '校内交易',
			value: '校内交易'
		}, {
			text: '全新正品',
			value: '全新正品'
		}, {
			text: '包邮',
			value: '包邮'
		}, {
			text: '不议价',
			value: '不议价'
		}, {
			text: '运费自理',
			value: '运费自理'
		}]
	})
	//校验规则
	let rules = reactive({
		name: {
			rules: [{
				required: true,
				errorMessage: '姓名不能为空'
			}]
		},
		price: {
			rules: [{
					required: true,
					errorMessage: '金额不能为空'
				},
				{
					format: 'number',
					errorMessage: '金额只能输入数字'
				},
			]
		},
		buy_price: {
			rules: [{
					required: true,
					errorMessage: '金额不能为空'
				},
				{
					format: 'number',
					errorMessage: '金额只能输入数字'
				},
			]
		},
		arr: {
			rules: [{
					format: 'array'
				},
				{
					validateFunction: function(rule, value, data, callback) {
						if (value.length < 2) {
							callback('请至少勾选两个兴趣爱好')
						}
						return true
					}
				}
			]
		}
	}, )
	//打开弹出框
	let inputDialog = ref(null)
	let dialogInputConfirm = async (val) => {
		// uni.showLoading({
		// 	title: '3秒后会关闭'
		// })
		console.log(val);
		hobbys.list.push({
			text: val,
			value: val
		})
		inputDialog.value.close()
	}


	//获取数据form表单数据
	let valiFormData = reactive({
		price: '',
		introduction: '',
		arr: [],
		buy_price: '',
	}, )
	//提交表单事件
	let uniRemind = (title, i) => {
		uni.showToast({
			title: title,
			icon: i
		})
	}
	let valiForm = ref(null)
	//收集数据
	let froms = reactive({
		forms: {
			title: '',
			textarea: ''
		},
		imageValue: []
	})
	let all = async () => {
		let all = reactive({
			obj: {
				title: froms.forms.title, //标题
				buy_price: valiFormData.buy_price, //购买价格
				transfer_price: valiFormData.price, //转让价格
				trading: valiFormData.arr, //标签
				desc: froms.forms.textarea, //商品介绍
				images: froms.imageValue, //图片
				category_id: [goodslist.list[idx.value]['_id'], ...goodslist.onselect] //分类以及详细分类id
			}
		})
		console.log(all.obj, '888888888888888');
		uni.request({
			url: 'http://127.0.0.1:3366/cp/addunusedgoods',
			data: all.obj,
			method: 'POST',
			success: ({
				data
			}) => {
				// console.log('原生的结果', data);
				uni.switchTab({
					url: '/pages/web/cp/Home'
				})
			},
			fail: (err) => {
				console.log('原生获取失败~');
			}
		})
	}
	let submits = async (ref) => {
		if (!froms.forms.title.length) return uniRemind('标题不可为空！', 'error')
		if (!froms.forms.textarea) return uniRemind('介绍不可为空！', 'error')
		valiForm.value.validate().then(res => {
			all()
			// console.log('验证通过');
		}).catch(err => {
			// console.log('执行hi');
			uniRemind('校验未通过', 'error')
		})
	}

	let uploads = (e) => {
		// froms.imageValue.push(e.tempFilePaths[0])
		uni.chooseImage({
			count: 5, //默认最多5张
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'], //从相册选择
			success(res) {
				let uploadTask = uni.uploadFile({
					url: 'http://127.0.0.1:3366/imgs',
					filePath: res.tempFilePaths[0],
					name: 'file',
					success(uploadres) {
						froms.imageValue.push(uploadres.data)
					}
				})
			}
		})
	}
</script>

<style scoped>
	.bt {
		border: 3px dashed #72a5fd;
		border-radius: 8px;
		height: 95px;
		width: 95px;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #ebf1f8;
		margin: 7px 7px;
	}

	.btimg {
		width: 36px;
		height: 36px;
	}

	.example-body {
		display: inline-flex;
		flex-wrap: wrap;
	}

	.imgs {
		width: 100px;
		height: 100px;
		border-radius: 6px;
		margin: 6px 7px;
	}

	.title {
		border-bottom: 1px solid #edf0f6;
		padding: 8px 0 8px 0;
		margin: 0 0 6px 0;
	}

	.top-cord {
		min-height: 45vh;
	}

	.area {
		width: 100%;
	}

	.two-cord {
		border: 1px solid red;
	}

	.item {
		/* 		border: 1px solid red; */
		padding: 6px 9px;
		margin: 5px;
		border-radius: 4px;
		background-color: #dadbe0;
		color: #fff;
	}

	.list {
		display: flex;
		flex-wrap: wrap;
		margin: 0 0 8px 0;
	}
</style>